<?php
/**
 * Created by PhpStorm.
 * User: jx
 * Date: 2018-01-15
 * Time: 22:51
 */
namespace app\common\traits;

trait Curd
{

    protected $condition;
    protected $order;
    protected $with;//关联预载入



    /**
     * find model
     * @param $id
     * @return mixed
     */
    protected  function findModel($id){

        $modelClass = $this->modelClass;
        $this->condition['id']=$id;
        $model = $modelClass::get($this->condition);

        if(!$model){
            error("你没权限操作或该记录已经被删除！");
        }
        return $model;
    }

    /**
     * find list
     * @return mixed
     */
    protected function prepareDataProvider(){
        $modelClass = $this->modelClass;

        // 条件
        if($this->condition){
            $query = $modelClass::where($this->condition);
        }

        // 排序
        if($this->order){
            if(isset($query)){
                $query = $query->order($this->order);
            }else{
                $query = $modelClass::order($this->order);
            }
        }

        // 关联预载入
        if($this->with){
            if(isset($query)){
                $query = $query->with($this->with);
            }else{
                $query = $modelClass::with($this->with);
            }
        }

        // 分页查询
        if(isset($query)){
            $list = $query->paginate(20);
        }else{
            $list = $modelClass::paginate(20);
        }
        return $list;
    }
    
    




}